﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace MVVM.Models.Services
{
    public class OrderService : IOrderService
    {
        public void SaveOrder(List<Dish> dishList)
        {
            string orderFile = System.IO.Path.Combine(Environment.CurrentDirectory, @"order\order.xml");
            if (!System.IO.Directory.Exists(orderFile))
	        {
                System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(orderFile));
	        }
            System.IO.FileStream saveStream = new System.IO.FileStream(orderFile, System.IO.FileMode.OpenOrCreate,
                System.IO.FileAccess.ReadWrite, System.IO.FileShare.None);

            XElement root;
            if (saveStream.Length > 0)
            {
                root = XElement.Load(saveStream);
                saveStream.Seek(0, System.IO.SeekOrigin.Begin);
            }
            else
            {
                root = new XElement("Orders");
            }
            XElement child = new XElement("Order");
            XAttribute orderDate = new XAttribute("Date", DateTime.Now.ToString());
            child.Add(orderDate);
            foreach (Dish item in dishList)
            {
                child.Add(new XElement("Dish",
                    new XElement("Name", item.Name),
                    new XElement("Category", item.Category),
                    new XElement("Comment", item.Comment),
                    new XElement("Score", item.Score.ToString()),
                    new XElement("Price", item.Price.ToString())
                    ));
            }
            root.Add(child);
            root.Save(saveStream);
            saveStream.Close();
        }
    }
}
